package com.lqzs.businessmanager.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.enableEdgeToEdge
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.lqzs.businessmanager.R
import org.greenrobot.eventbus.EventBus

abstract class BaseActivity <VB : ViewBinding,VM : BaseViewModel>(@LayoutRes private val layoutId: Int): AppCompatActivity() {

    private var _binding: VB? = null
    protected val binding get() = _binding!!
    protected var mViewModel:VM = createViewModel()

    @SuppressLint("QueryPermissionsNeeded")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        _binding  = createViewBinding(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        if (isRegisterEventBus())
            EventBus.getDefault().register(this)
        initView()
        initListener()
    }

    protected open fun initView(){

    }

    protected open fun initListener(){

    }

    /**
     * 是否注册eventbus事件
     *
     * @return
     */
    open fun isRegisterEventBus(): Boolean {
        return false
    }

    abstract fun createViewBinding(view: LayoutInflater): VB?

    abstract fun createViewModel(): VM

    override fun onDestroy() {
        super.onDestroy()
        if (isRegisterEventBus())
            EventBus.getDefault().unregister(this)
    }

}